﻿namespace SimOne.SharePoint.WebControls {
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.WebControls;
    using System.Collections.Generic;

    public static class PeoplePickerHelper {
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="peoplePicker">用户选择器</param>
        /// <returns>用户列表</returns>
        public static IEnumerable<SPUser> GetUsers(this ClientPeoplePicker peoplePicker, SPWeb web) {
            foreach (PickerEntity entity in peoplePicker.ResolvedEntities) {
                string loginName = entity.Key;
                SPUser user = web.Site.RootWeb.EnsureUser(loginName);
                yield return user;
            }
        }

        /// <summary>
        /// 设置用户
        /// </summary>
        /// <param name="peoplePicker">用户选择器</param>
        /// <param name="users">用户列表</param>
        public static void SetUsers(this ClientPeoplePicker peoplePicker, IEnumerable<SPUser> users, SPWeb web) {
            List<PickerEntity> entities = new List<PickerEntity>();
            PeopleEditor peopleEditor = new PeopleEditor();
            foreach (SPUser user in users) {
                PickerEntity entity = new PickerEntity();
                entity.Key = user.LoginName;
                entity = peopleEditor.ValidateEntity(entity);
                entity.IsResolved = true;
                entities.Add(entity);
            }
            peoplePicker.AddEntities(entities);
        }
    }
}